<?php
/**
 * “发布公告”页面的回调函数
 */
function investigatedepartment_create_page(){
	  //我们为这个页面设置标题
	 drupal_set_title('尽调机构信息管理');
	 global $user;  
	 
	 $query = "SELECT id FROM " .
           "{investigate_department} where userid = ?";
 	 $queryResult = db_query($query, array($user->uid));
	 $ifempty =TRUE;
	 $pageid ='';
	  foreach ($queryResult as $links ) {
	  	$pageid =$links->id;
	  	if($pageid > 0)
		  	$ifempty = FALSE;
	  }
	 if($ifempty)
	 {
	 	 $render_array = array(
	   		'#markup' => '',
		 );
	 
		 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
		 $form = drupal_get_form('investigatedepartment_create_form');
		 $render_array['#markup'] .= drupal_render($form);
	 }
	 else{
	 	 $render_array = array(
	   		'#markup' => '',
		 );
	 
		$form = drupal_get_form('investigatedepartment_edit_form',$pageid);
  		$render_array['#markup'] .= drupal_render($form);
	 }	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function investigatedepartment_create_form(){	 
	  //提示信息，默认为markup类型。
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 //表单元素“姓名”
	 $form['department_name'] = array(
	  '#title' => t('部门名称'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['investigatedepartment_create_form']['department_name'])?$_SESSION['investigatedepartment_create_form']['department_name']:"",
	 );
	 
	 $form['principal_name'] = array(
	  '#title' => t('负责人姓名'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['investigatedepartment_create_form']['principal_name'])?$_SESSION['investigatedepartment_create_form']['principal_name']:"",
	 );
	 $form['superior'] = array(
	  '#title' => t('上级部门'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['investigatedepartment_create_form']['superior'])?$_SESSION['investigatedepartment_create_form']['superior']:"",
	 );
	 
	  $form['mail'] = array(
	  '#title' => t('邮箱地址'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['investigatedepartment_create_form']['mail'])?$_SESSION['investigatedepartment_create_form']['mail']:"",
	 );
	 
	 $form['phone'] = array(
	  '#title' => t('联系电话'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['investigatedepartment_create_form']['phone'])?$_SESSION['investigatedepartment_create_form']['phone']:"",
	 );
	 
	 $form['function'] = array(
	  '#title' => t('部门职能'),
	  '#type' => 'textarea',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['investigatedepartment_create_form']['function'])?$_SESSION['investigatedepartment_create_form']['function']:"",
	 );
	 	 
	 $form['remarks'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['investigatedepartment_create_form']['remarks'])?$_SESSION['investigatedepartment_create_form']['remarks']:"",
	 );
	 	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function investigatedepartment_create_form_validate($form, &$form_state){
	 if(!preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $form_state['values']['mail'])){
	  form_set_error('mail',t('您输入的电子邮件地址格式不正确'));
	 }
	  if (drupal_strlen($form_state['values']['principal_name']) < 2) {
	    form_set_error('name', '您输入的负责人姓名长度太短，请填写真实姓名。');
	  }
  
}

function investigatedepartment_create_form_submit($form, &$form_state){
	  //把表单的值存放在会话中去，由于这里涉及到了两个不同的表单之间传值。
	 $_SESSION['investigatedepartment_create_form'] = $form_state['values'];
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'investigatedepartment/create/confirm';
}

function investigatedepartment_confirm_page(){
  //我们为这个页面设置标题
	 drupal_set_title('提交尽调机构信息预览');
	 
	 //这里首先作了判断，如果会话中没有设置contactus_form，返回contactus
	 if(empty($_SESSION['investigatedepartment_create_form'])){
	  drupal_goto('investigatedepartment/create');
	 }
	 $render_array = array(
	   '#markup' => '', 
	 );
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('investigatedepartment_confirm_form');
	 $render_array['#markup'] .= drupal_render($form);
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function investigatedepartment_confirm_form(){
 $form['department_name'] = array(
  '#title' => t('部门名称'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['investigatedepartment_create_form']['department_name'])?$_SESSION['investigatedepartment_create_form']['department_name']:"",
 );
 
 $form['principal_name'] = array(
  '#title' => t('负责人名称'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['investigatedepartment_create_form']['principal_name'])?$_SESSION['investigatedepartment_create_form']['principal_name']:"",
 );

 $form['superior'] = array(
  '#title' => t('上级部门'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['investigatedepartment_create_form']['superior'])?$_SESSION['investigatedepartment_create_form']['superior']:"",
 );
   
 $form['mail'] = array(
  '#title' => t('邮箱地址'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['investigatedepartment_create_form']['mail'])?$_SESSION['investigatedepartment_create_form']['mail']:"",
 );
 
 $form['phone'] = array(
  '#title' => t('联系电话'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['investigatedepartment_create_form']['phone'])?$_SESSION['investigatedepartment_create_form']['phone']:"",
 );
  
 $form['function'] = array(
  '#title' => t('部门职能'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['investigatedepartment_create_form']['function'])?$_SESSION['investigatedepartment_create_form']['function']:"",
 );
 
 $form['remarks'] = array(
  '#title' => t('备注'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['investigatedepartment_create_form']['remarks'])?$_SESSION['investigatedepartment_create_form']['remarks']:"",
 );
  
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('返回'),
    '#submit' => array('investigatedepartment_confirm_form_back'),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('提交'),
  );
  
  return $form;
}

function investigatedepartment_confirm_form_back($form, &$form_state){
  //简单的重定向到contactus页面
 $form_state['redirect'] = 'investigatedepartment/create';
}

function investigatedepartment_confirm_form_submit($form, &$form_state){
		/**
	   * 写入数据库
	   */
	   $values = NULL;
	   //从会话中获取用户最初提交的值，并将$_SESSION['contactus_form']置为空。
	  if(empty($_SESSION['investigatedepartment_create_form'])){
		  //drupal_goto('contact');
		  $form_state['redirect'] = 'investigatedepartment/create';
	  }else{
		  $values = $_SESSION['investigatedepartment_create_form'];
		  unset($_SESSION['investigatedepartment_create_form']);
	  }
	  global $user;
	  $last_id = db_insert('investigate_department')
  		->fields(array(
  		     'userid'=> $user->uid,
   			 'department_name' => $values['department_name'],
   			 'principal_name' => $values['principal_name'],
   			 'phone' => $values['phone'],
   			 'mail' => $values['mail'],
   			 'superior' =>  $values['superior'],
   			 'function' =>  $values['function'],
   			 'remarks' => $values['remarks'],
  			))->execute();
	  if ($last_id!=NULL) {
	    
	    /**
	     * 执行成功了，到数据库去看看，是不是有这条记录了
	     * 显示一条信息给用户
	     */
		 $form_state['redirect'] = 'investigatedepartment/edit/'.$last_id;
		 	    
	  } else {
	    
	    // 数据写入失败了
	    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
	    
	  }
		
	
}

function investigatedepartment_list_page() {
 $header = array(
      array('data' => '部门名称', 'field' => 'department_name', 'sort' => 'desc'),
      array('data' => '负责人名称', 'field' => 'principal_name'),
      array('data' => '上级部门', 'field' => 'superior'),
      array('data' => '电话', 'field' => 'phone'),
      array('data' => '邮箱', 'field' => 'mail'),
      array('data' => '部门职能', 'field' => 'function'),
     // array('data' => '备注', 'field' => 'remarks'),
      );
  $query = db_select('investigate_department', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'department_name',
      'principal_name',
      'superior',
      'phone',
      'mail',
      'function',
      //'remarks',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->department_name, 'investigatedepartment/edit/'. $node->id),
        $node->principal_name,
        $node->superior,
        $node->phone,
        $node->mail,
        $node->function,
        //$node->remarks,
      )
      );
  }
  $html = theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有尽调机构信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

function investigatedepartment_list_perpage($perid) {
  // content variable that will be returned for display
  $page_content = '';
  $page_content .= l('查看尽调机构信息列表','investigatedepartment/list') . '<br />'. '<br />';
  
  $query = "SELECT department_name,principal_name,superior,phone,mail,function,remarks FROM " .
           "{investigate_department} where id = ?";
  $queryResult = db_query($query, array($perid));
  foreach ($queryResult as $links ) { 
    $page_content .= '<h5>部门名称：'.$links->department_name.'</h5><br />';
	$page_content .= '<h5>负责人名称：'.$links->principal_name.'</h5><br />';
	$page_content .= '<h5>上级部门'.$links->superior.'</h5><br />';
	$page_content .= '<h5>联系电话：'.$links->phone.'</h5><br />';
	$page_content .= '<h5>邮箱地址：'.$links->mail.'</h5><br />';
    $page_content .= '<h5>部门职能：'.$links->function.'</h5><br />';
    $page_content .= '<h5>备注：'.$links->remarks.'</h5><br />';
	$page_content = str_replace(array("\n", "\r\n") , "<BR />", $page_content);
  }
  // More coming....
  if ($page_content == '') {
    $page_content = "没有该尽调机构信息.";
  }

  return $page_content;
}

function investigatedepartment_edit_page($perid) {
  $page_content = '';
  if(user_access('view investigate department'))
  	$page_content .= l('查看尽调机构信息列表','investigatedepartment/list') . '<br />'. '<br />';
  drupal_set_title('尽调机构信息管理');
	 
	 $query = "SELECT id FROM " .
           "{investigate_department} where id = ?";
 	 $queryResult = db_query($query, array($perid));
	 $ifempty =TRUE;
	  foreach ($queryResult as $links ) {
	  	if($links->id>0)
		  	$ifempty = FALSE;
	  }
	 if($ifempty)
	 {
	 	 $render_array = array(
	   		'#markup' => '',
		 );
	 
		 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
		 $form = drupal_get_form('investigatedepartment_create_form');
		 $render_array['#markup'] .= drupal_render($form);
	 }
	 else{
	 	 $render_array = array(
	   		'#markup' => $page_content,
		 );
	 
		$form = drupal_get_form('investigatedepartment_edit_form',$perid);
  		$render_array['#markup'] .= drupal_render($form);
	 }	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function investigatedepartment_edit_form($form, &$form_state, $perid){
  
  $query = "SELECT department_name,principal_name,phone,mail,superior,function,remarks FROM " .
           "{investigate_department} where id = ?";
  $queryResult = db_query($query, array($perid));
 
  $department_name = '';
  $principal_name = '';
  $phone = '';
  $mail = ''; 
  $superior = '';
  $function = '';
  $remarks = '';
  
  foreach ($queryResult as $links ) {
  	$department_name = $links->department_name;
    $principal_name = $links->principal_name;
	$phone = $links->phone;
    $mail = $links->mail;
	$superior = $links->superior;
	$function = $links->function;
    $remarks = $links->remarks;
  }
   $form['bid'] = array('#type' => 'hidden', '#value' => $perid);
   $form['department_name'] = array(
	  '#title' => t('部门名称'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['investigatedepartment_create_form']['department_name'])?$_SESSION['investigatedepartment_create_form']['department_name']:$department_name,
	 );
	 
	 $form['principal_name'] = array(
	  '#title' => t('负责人姓名'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['investigatedepartment_create_form']['principal_name'])?$_SESSION['investigatedepartment_create_form']['principal_name']:$principal_name,
	 );
	 $form['superior'] = array(
	  '#title' => t('上级部门'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['investigatedepartment_create_form']['superior'])?$_SESSION['investigatedepartment_create_form']['superior']:$superior,
	 );
	 
	  $form['mail'] = array(
	  '#title' => t('邮箱地址'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['investigatedepartment_create_form']['mail'])?$_SESSION['investigatedepartment_create_form']['mail']:$mail,
	 );
	 
	 $form['phone'] = array(
	  '#title' => t('联系电话'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['investigatedepartment_create_form']['phone'])?$_SESSION['investigatedepartment_create_form']['phone']:$phone,
	 );
	 
	 $form['function'] = array(
	  '#title' => t('部门职能'),
	  '#type' => 'textarea',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['investigatedepartment_create_form']['function'])?$_SESSION['investigatedepartment_create_form']['function']:$function,
	 );
	 	 
	 $form['remarks'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['investigatedepartment_create_form']['remarks'])?$_SESSION['investigatedepartment_create_form']['remarks']:$remarks,
	 );
	
	  $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    '#value' => t('删除尽调机构信息'),
	    '#submit' => array('investigatedepartment_edit_form_deleate'),
	  );
  return $form;
}

function investigatedepartment_edit_form_submit($form, &$form_state){
	  $values = NULL;
	  $values = $form_state['values'];		
	  db_update('investigate_department')
  		->fields(array(
   			 'department_name' => $values['department_name'],
   			 'principal_name' => $values['principal_name'],
   			 'phone' => $values['phone'],
   			 'mail' => $values['mail'],
   			 'superior' =>  $values['superior'],
   			 'function' =>  $values['function'],
   			 'remarks' => $values['remarks'],
  			))
  		->condition('id', $values['bid'])
  		->execute();
	 $form_state['redirect'] = 'investigatedepartment/edit/'.$values['bid'];
}

function investigatedepartment_edit_form_deleate($form, &$form_state){
	 $values = NULL;
	 $_SESSION['investigatedepartment_edit_form'] = $form_state['values'];
	 $values = $_SESSION['investigatedepartment_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'investigatedepartment/deleate/'.$values['bid'];
}

function investigatedepartment_deleate_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后尽调机构信息将不可恢复！';
  
  drupal_set_title('删除尽调机构信息');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('investigatedepartment_deleate_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function investigatedepartment_deleate_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('investigatedepartment_deleate_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function investigatedepartment_deleate_form_back($form, &$form_state){
	if(empty($_SESSION['investigatedepartment_edit_form'])){
		  if(user_access('view investigate department'))
		  	$form_state['redirect'] = 'investigatedepartment/list';
		  else{
		  	$form_state['redirect'] = 'investigatedepartment/create';
		  }
	  }else{
		  $values = $_SESSION['investigatedepartment_edit_form'];
		  unset($_SESSION['investigatedepartment_edit_form']);
		  $form_state['redirect'] = 'investigatedepartment/edit/'.$values['bid'];
	  }
}

function investigatedepartment_deleate_form_submit($form, &$form_state){
  //简单的重定向到contactus页面
 if(empty($_SESSION['investigatedepartment_edit_form'])){
		  //drupal_goto('contact');
		   if(user_access('view investigate department'))
		  	$form_state['redirect'] = 'investigatedepartment/list';
		  else{
		  	$form_state['redirect'] = 'investigatedepartment/create';
		  }
	  }else{
		  $values = $_SESSION['investigatedepartment_edit_form'];
		  unset($_SESSION['investigatedepartment_edit_form']);
		  db_delete('investigate_department')
			->condition('id' ,$values['bid'])
			->execute();
		  if(user_access('view investigate department'))
		  	$form_state['redirect'] = 'investigatedepartment/list';
		  else
		  	$form_state['redirect'] = 'investigatedepartment/create';
	  }

}

function investigatedepartment_choose_page($perid) {
  drupal_set_title('尽调机构选择管理');
  $page_content = '';
  $page_content .= l('返回基金列表','guidingfund/guidingfund_investigationset_page') . '<br />'. '<br />';

  //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
  $render_array = array(
  		'#markup' => $page_content,
  );
  $form = drupal_get_form('investigatedepartment_choose_form', $perid);
  $render_array['#markup'] .= drupal_render($form ); 
  
  return $render_array; 
}

function investigatedepartment_choose_form($form, &$form_state, $perid){
  $query = "SELECT inve_department_list FROM " .
           "{guiding_fund_info} where id = ?";
  $inve_department_list = db_query($query, array($perid));	
  $departments = array();
  foreach ($inve_department_list as $department) {
      $departments = explode(',',$department->inve_department_list);
  }
  $query = "SELECT id,department_name, principal_name,superior,function FROM " .
           "{investigate_department}";
  $queryResult = db_query($query);	
  
  $header = array(
    'department_name' => t('部门名称'),
    'principal_name' => t('负责人名称'),
    'superior' => t('上级部门'),
    'function' => t('部门职能'),
    'state' => t('状态(空表示未被选择)'),
  );
  $options = array();
  foreach ($queryResult as $node) {
  	$state = '';
  	if(in_array($node->id,$departments, TRUE)&&$departments!=NULL){
  		$state=  '已选择';
  	}
    $options[$node->id] =array(
      'department_name' => l($node->department_name, 'investigatedepartment/list/'. $node->id),
      'principal_name' => $node->principal_name,
      'superior' => $node->superior,
      'function' => $node->function,
      'state' => $state,   
    );
  }
  $form['bid'] = array('#type' => 'hidden', '#value' => $perid);
  $form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#empty' => t('没有评审机构记录'),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('提交'),
  );
  return $form;  
}

function investigatedepartment_choose_form_submit($form, &$form_state){
	 $values = NULL;
	 $values = $form_state['values'];		
	 $inve_department_list = '';
	 foreach ($values['table'] as $rows) {
         $inve_department_list.=$rows.',';
     }
	  db_update('guiding_fund_info')
  		->fields(array(
   			 'inve_department_list' => $inve_department_list,
  			))
  		->condition('id', $values['bid'])
  		->execute();
	 $form_state['redirect'] = 'investigatedepartment/choose/'.$values['bid'];	
	 
}

//////
//尽调内容模板设置
//////
function investigate_template_set_page() {
 $html = '';
 if(user_access('edit guiding fund information')){
 	 $html .= l('创建基金','guidingfund/create') . '<br />'. '<br />'; 
 }

 $header = array(
      array('data' => '基金名称', 'field' => 'name'),
      array('data' => '负责人', 'field' => 'principal_name'),
      array('data' => '成立时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '尽调内容反馈格式设置', 'field' => 'announce_id'),
      );
  $query = db_select('guiding_fund_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'principal_name',
      'timestamp',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
  
	 $title = '没有上传记录';
	 if(user_access('view investigate department')){
		 $title = l('上传尽调内容反馈格式模板','investigate_template/create/'. $node->id);
	 }
	 
	  $query = "SELECT id , name FROM " .
	           "{investigate_file_info} where guiding_fund_id = ? and type = ?";
	  $queryResult = db_query($query, array( $node->id, 0));
	  foreach ($queryResult as $template) {
	  if($template->id>0)
		  {  	
			$title = l($template->name,'investigate_file/list/'.$template->id);	
		  }
	  }
	  $rows[] = array(
	      'data' => array(
	        l($node->name, 'guidingfund/list/'. $node->id),
	        $node->principal_name,
	        format_date($node->timestamp, 'custom', 'D, Y-m-d'),
	        $title,
	      )
	      );
	  //}
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

function investigate_template_create_page($fundid){
	 drupal_set_title('尽调材料提交');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('investigate_template_create_form',$fundid);
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function investigate_template_create_form($form, &$form_state, $fundid){
	 $form['bid'] = array('#type' => 'hidden', '#value' => $fundid);	 
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['upload'] = array(
		'#type' => 'managed_file',
		'#title' => '尽调材料',
		'#required' => TRUE,
		'#upload_location' => 'public://my_uploads',
		'#upload_validators' => array(	
	      'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		  'file_validate_size' => array(20*1024*1024)),
	);
	
   if(!user_access('view investigate department')){
   	$form['state'] = array(
	  '#title' => t('尽调结果'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
   }
	 
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function investigate_template_create_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
			$type = 1;
			$query = "SELECT id, name FROM " .
		           "{guiding_fund_info} where id = ? ";
		    $queryResult = db_query($query, array($values['bid'] ));
			$fundname = '';
			
			foreach ($queryResult as $links ) {
				if($links->id>0){
					$fundname = $links->name;
				}
			}
			$investigate_name = '';
			$state = '';
			if(user_access('view investigate department')){
			 	$type=0;
				$filename .= $fundname."_尽调内容格式模板";
			}  
			else{
				$query = "SELECT  name FROM " .
		           "{users} where uid = ? ";
		   		$queryResult = db_query($query, array($user->uid));
				foreach ($queryResult as $username ) {
					$filename .= $username->name."_尽调结果提交材料";
				}
				
				$query = "SELECT id, department_name FROM " .
		           "{investigate_department} where userid = ? ";
			    $queryResult = db_query($query, array($user->uid));	
				foreach ($queryResult as $links ) {
					if($links->id>0){
						$investigate_name = $links->department_name;
					}
				}
				$state = $values['state'];
			}
			$query = "SELECT id,file_managed_id FROM " .
		           "{investigate_file_info} where user_id = ? and guiding_fund_id = ?";
		    $file_managed_id = '';  //已上传申报材料在file_managed表中对应的id
		    $queryResult = db_query($query, array($user->uid, $values['bid'] ));
			$uploadid = 0; //已上传申报材料id
			foreach ($queryResult as $links ) {
				if($links->id>0){
					$file_managed_id = $links->file_managed_id;
					$uploadid = $links->id;
				}
			}
			if($uploadid==0){
				$last_id = db_insert('investigate_file_info')
			  		->fields(array(
			   			 'name' => $filename,
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'investigate_name' => $investigate_name,
			   			 'remark' => $values['remark'],
			   			 'guiding_fund_id' => $values['bid'],
			   			 'user_id' => $user->uid,
			   			 'type' => $type,
			   			 'file_managed_id' => $fid,
			   			 'state' => $state,
			   			 'reply_id' => $values['bid'],
			  			))->execute();
				  if ($last_id!=NULL) {
				  	if(user_access('view investigate department'))
					 	$form_state['redirect'] = 'investigate/templatesetpage';
					else{
						$form_state['redirect'] = 'investigate/graded/list';
					} 
					
					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
			}
			else{
				if($file_managed_id>0){
					$file = file_load($file_managed_id);
				  if($file!=NULL){
					 file_delete($file);
				  }
					db_delete('file_managed')
				    ->condition('fid',$file_managed_id)
					->execute();
				}	
				db_update('apply_file_info')
			  		->fields(array(
			   			 'name' => $filename,
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'remark' => $values['remark'],
			   			 'guiding_fund_id' => $values['bid'],
			   			 'type' => $type,
			   			 'file_managed_id' => $fid,
			   			 'state' => $values['state'],
			  			))
			  		->condition('id',$uploadid)
			  		->execute();
				
				if(user_access('view investigate department'))
					 	$form_state['redirect'] = 'investigate/templatesetpage';
					else{
						$form_state['redirect'] = 'investigate/graded/list';
					} 
			}
			
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

//尽调内容或模板浏览
function investigate_file_list_page($perid) {
  // content variable that will be returned for display
  $page_content = '';
  
  global $user;
  $query = "SELECT id, name,url,timestamp,remark, guiding_fund_id,user_id,type,investigate_name,state,reply_id FROM " .
           "{investigate_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  foreach ($queryResult as $links ) {
  	if($links->user_id != $user->uid &&$links->type != 0) {
  		if(!user_access('edit guiding fund information')){
  			$query = "SELECT id, name,url,timestamp,remark, guiding_fund_id,user_id,type,investigate_name,state,reply_id FROM " .
           		"{investigate_file_info} where user_id = ?";
			$queryResult = db_query($query, array($user->uid));
			foreach ($queryResult as $insidelinks ) {
				$links = $insidelinks;
			}
  		}
  	}
	
   if($links->type != 1 && user_access('edit guiding fund information')){
 		$page_content .= l('切换成编辑模式','investigate_file/edit/'.$perid) . '<br />'. '<br />'; 
 	}
   else if($links->type == 1 && $links->user_id == $user->uid)
   {
  	 	$page_content .= l('切换成编辑模式','investigate_file/edit/'.$perid) . '<br />'. '<br />'; 
   }
   
	$page_content .= l('查看基金信息','investigate/templatesetpage') . '<br />'. '<br />';
	if($links->type == 0) {
    	$page_content .= '<h5>尽调内容格式模板下载:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/drupal/sites/default/files/'.$links->url).'<br />'.'<br />';
		$page_content .= '<h5>上传时间:</h5>'. format_date($links->timestamp, 'custom', 'D, Y-m-d').'<br />'.'<br />';
    	$page_content .= '<h5>备注: </h5>'.$links->remark.'<br />'.'<br />';
    }	
	else if($links->type == 1) {
		$page_content .= '<h5>尽调结果材料下载:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/drupal/sites/default/files/'.$links->url).'<br />'.'<br />';
		$page_content .= '<h5>尽调机构:</h5>'.$links->investigate_name.'<br />'.'<br />';
		$page_content .= '<h5>上传时间: </h5>'. format_date($links->timestamp, 'custom', 'D, Y-m-d').'<br />'.'<br />';
		$page_content .= '<h5>尽调结果:</h5>'.$links->state.'<br />'.'<br />';
    	$page_content .= '<h5>备注:</h5>'.$links->remark.'<br />'.'<br />';
	}
  }
  // More coming....
  if ($page_content == '') {
    $page_content = "没有该上传申报材料信息.";
  }

  return $page_content;
}

//尽调内容或模板编辑
function investigate_file_edit_perpage($perid) {
  $page_content = '';
  $page_content .= l('查看基金信息','investigate/templatesetpage') . '<br />'. '<br />';
  $page_content .= l('切换成浏览模式','investigate_file/list/'.$perid) . '<br />'. '<br />'; 	
  drupal_set_title('尽调材料管理');
	 
  $query = "SELECT id,name, url FROM " .
           "{investigate_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty =TRUE;
  foreach ($queryResult as $links ) {
	  if($links->id>0)
		  $ifempty = FALSE;
  }
  if($ifempty)
	 {
	 	 $render_array = array(
	   		'#markup' => '',
		 );
	 
		 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
		 $form = drupal_get_form('investigate_template_create_form');
		 $render_array['#markup'] .= drupal_render($form);
	 }
 else{
	 	 $page_content .= '<h5>已提交尽调结果材料:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/drupal/sites/default/files/'.$links->url).'<br />'.'<br />';
	     $render_array = array(
	   		'#markup' => $page_content,
		 );
	 
		$form = drupal_get_form('investigate_file_edit_form',$perid);
  		$render_array['#markup'] .= drupal_render($form);
	 }	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function investigate_file_edit_form($form, &$form_state, $perid){
  
  $query = "SELECT id, name,url,remark, guiding_fund_id,user_id,type,reply_id,investigate_name,state,file_managed_id FROM " .
           "{investigate_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
 
  $name = '';
  $url = '';
  $remark = ''; 
  $guiding_fund_id = '';
  $type = '';
  $reply_id = '';
  $investigate_name = '';
  $state = '';
  global $user;
 foreach ($queryResult as $links ) {
  	if($links->user_id != $user->uid){
  		if(!user_access('edit guiding fund information')){
  			$query = "SELECT id, name,url,remark, guiding_fund_id,user_id,type,reply_id,investigate_name,state,file_managed_id FROM " .
           		"{investigate_file_info} where user_id = ?";
			$queryResult = db_query($query, array($user->uid));
			foreach ($queryResult as $insidelinks ) {
				$links = $insidelinks;
			}
  		}
  	}
	
	$name =  $links->name;
	$url =  $links->url;
    $remark =  $links->remark;
	$guiding_fund_id =  $links->guiding_fund_id;
	$type =  $links->type;
	$reply_id = $links->reply_id;
  	$investigate_name = $links->investigate_name;
  	$state = $links->state;
	$file_managed_id = $links->file_managed_id;
  }
   if($type == 1){
   	$form['bid'] = array('#type' => 'hidden', '#value' => $perid);
   	$form['type'] = array('#type' => 'hidden', '#value' => $type);
	$form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id);
	$form['guiding_fund_id'] = array('#type' => 'hidden', '#value' => $guiding_fund_id);
	
	$form['name'] = array(
	  '#title' => t('文件名'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['investigate_file_edit_form']['name'])?$_SESSION['investigate_file_edit_form']['name']:$name,
	 );
	 
    $form['investigate_name'] = array(
	  '#title' => t('尽调机构名称'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['investigate_file_edit_form']['investigate_name'])?$_SESSION['investigate_file_edit_form']['investigate_name']:$investigate_name,
	 );
	 
	 $form['upload'] = array(
	  '#type' => 'managed_file',
	  '#title' => '重新提交尽调结果材料',
	  '#required' => FAlSE,
	  '#upload_location' => 'public://my_uploads',
	  '#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	 $form['state'] = array(
	  '#title' => t('评审结果'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['investigate_file_edit_form']['state'])?$_SESSION['investigate_file_edit_form']['state']:$state,
	 );
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['investigate_file_edit_form']['remark'])?$_SESSION['investigate_file_edit_form']['remark']:$remark,
	 );
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    '#value' => t('删除该材料'),
	    '#submit' => array('investigate_file_edit_form_deleate'),
	  );
   }	
	else if($type == 0){
	   	$form['bid'] = array('#type' => 'hidden', '#value' => $perid);
	   	$form['type'] = array('#type' => 'hidden', '#value' => $type);
		$form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id);
		$form['guiding_fund_id'] = array('#type' => 'hidden', '#value' => $guiding_fund_id);
		
		$form['name'] = array(
		  '#title' => t('文件名'),
		  '#type' => 'textfield',
		  '#required' => TRUE,
		  '#default_value' =>isset($_SESSION['investigate_file_edit_form']['name'])?$_SESSION['investigate_file_edit_form']['name']:$name,
		 );
		 
		 $form['upload'] = array(
		  '#type' => 'managed_file',
		  '#title' => '重新提交禁掉材料模板',
		  '#required' => FAlSE,
		  '#upload_location' => 'public://my_uploads',
		  '#upload_validators' => array(
		    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
			'file_validate_size' => array(20*1024*1024)),
		);
		
		 $form['remark'] = array(
		  '#title' => t('备注'),
		  '#type' => 'textarea',
		  '#required' => FALSE,
		  '#default_value' =>isset($_SESSION['investigate_file_edit_form']['remark'])?$_SESSION['investigate_file_edit_form']['remark']:$remark,
		 );
		 
		 $form['submit'] = array(
		    '#type' => 'submit',
		    '#value' => t('提交修改'),
		  );
		 //表单元素“提交”按钮
		  $form['deleate'] = array(
		    '#type' => 'submit',
		    '#value' => t('删除该模板'),
		    '#submit' => array('investigate_file_edit_form_deleate'),
		  );
   	  }
	  
  return $form;
}

function investigate_file_edit_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  

	
	global $user; 
	$filetype = $values['type'];
	$filename = $values['name'];
	$filemanagedid = $values['file_managed_id'];
	$uploadid = $values['bid'];
	if ($file != null) {
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
								
			if($filemanagedid>0){
				$file = file_load($filemanagedid);
				  if($file!=NULL){
					 file_delete($file);
				  }
				db_delete('file_managed')
				  ->condition('fid',$filemanagedid)
				  ->execute();
			}	
			if($filetype == 1){
				db_update('investigate_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'url' => $saveurl,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			   	    'state' => $values['state'],
			   	    'file_managed_id' => $fid,
			   	    'investigate_name' => $values['investigate_name'],
			  		))
			  		->condition('id',$uploadid)
			  		->execute();				
			}
			else  if($filetype == 0){
				db_update('investigate_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'url' => $saveurl,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			   	    'file_managed_id' => $fid,
			  		))
			  		->condition('id',$uploadid)
			  		->execute();
							
			}			
			$form_state['redirect'] = 'investigate_file/list/'.$values['bid'];
		}			
		else {
			form_set_error('upload',$extension_errors[0]); 
		}
	}
	else{
			if($filetype == 1){
				db_update('investigate_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			   	    'state' => $values['state'],
			   	    'investigate_name' => $values['investigate_name'],
			  		))
			  		->condition('id',$uploadid)
			  		->execute();				
			}
			else  if($filetype == 0){
				db_update('investigate_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			  		))
			  		->condition('id',$uploadid)
			  		->execute();			
			}			
			$form_state['redirect'] = 'investigate_file/list/'.$values['bid'];
	}
}

function investigate_file_edit_form_deleate($form, &$form_state){
	 $values = NULL;
	 $_SESSION['investigate_file_edit_form'] = $form_state['values'];
	 $values = $_SESSION['investigate_file_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'applyfile/deleate/'.$values['bid'];
}

function investigate_file_deleate_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后该内容将不可恢复！';
  
  drupal_set_title('删除尽调材料内容');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('investigatefile_deleate_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function investigatefile_deleate_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('investigatefile_deleate_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function investigatefile_deleate_form_back($form, &$form_state){
	if(empty($_SESSION['applyfile_edit_form'])){
		  	$form_state['redirect'] = 'applyfile/list';
	  }else{
		  $values = $_SESSION['applyfile_edit_form'];
		  unset($_SESSION['applyfile_edit_form']);
		  $form_state['redirect'] = 'applyfile/edit/'.$values['bid'];
	  }
}

function investigatefile_deleate_form_submit($form, &$form_state){
 if(empty($_SESSION['investigate_file_edit_form'])){
		  $form_state['redirect'] = 'guidingfund/list';
	  }else{
		  $values = $_SESSION['investigate_file_edit_form'];
		  unset($_SESSION['investigate_file_edit_form']);
		  $file = file_load($values['file_managed_id']);
				  if($file!=NULL){
					 file_delete($file);
				  }
		  db_delete('file_managed')
				  ->condition('fid',$values['file_managed_id'])
				  ->execute();
		  db_delete('investigate_file_info')
			->condition('id' ,$values['bid'])
			->execute();
			
		  $form_state['redirect'] = 'guidingfund/list';

	  }

}

//基金对应申报材料及模板
function investigate_file_guidingfund_page($perid) {
  // content variable that will be returned for display
  $html = '';
  $html .= l('查看基金信息','guidingfund/guidingfund_investigationset_page') . '<br />'. '<br />';
  $header = array(
      array('data' => '已上传尽调材料模板', 'field' => 'name',),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      );
  $query = db_select('investigate_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      ))
	  ->condition('guiding_fund_id',$perid,'=')
	  ->condition('type',0,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'investigate_file/list/'. $node->id),
        format_date($node->timestamp, 'custom', 'D, Y-m-d'),
        $node->remark,
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
	  
  $header = array(
      array('data' => '已上传尽调结果材料', 'field' => 'name'),
      array('data' => '尽调机构', 'field' => 'apply_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '尽调结果', 'field' => 'state'),
      );
  $query = db_select('investigate_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'investigate_name',
      'state',
      'reply_id',
      ))
	  ->condition('guiding_fund_id',$perid,'=')
	  ->condition('type',1,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'applyfile/list/'. $node->id),
        $node->investigate_name,
        format_date($node->timestamp, 'custom', 'D, Y-m-d'),
        $node->remark,
        $node->state,
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

function investigate_graded_list_page() {
 $html = ''; 
  global $user;
  $query = "SELECT id  FROM " .
	   "{investigate_department} where  userid = ?";
  $queryResult = db_query($query, array($user->uid));
  $inve_id = '';
  foreach ($queryResult as $template) {
	 if($template->id>0)
	 {  	
		$inve_id = $template->id;	
	 }
  }
 if($inve_id>0){
 
 $header = array(
      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
      array('data' => '负责人', 'field' => 'principal_name'),
      array('data' => '成立时间', 'field' => 'timestamp'),
      array('data' => '尽调结果编辑'),
      );
	$query = db_select('guiding_fund_info', 'n')
	      ->extend('PagerDefault') //Pager Extender
	      ->limit(15)//10 results per page
	      ->extend('TableSort')//Sorting Extender
	      ->orderByHeader($header)//Field to sort on is picked from $header
	      ->fields ('n', array (
	      'id',
	      'name',
	      'principal_name',
	      'timestamp',
	      ));
	  $results = $query
	      ->execute();
	  	  
	  $rows = array();
  foreach ($results as $node) {
  	      $title = '';
		  if(!user_access('view investigate department')){
			  $query = "SELECT inve_department_list FROM " .
			           "{guiding_fund_info} where id = ?";
			  $inve_department_list = db_query($query, array($node->id));	
			  $departments = array();
			  foreach ($inve_department_list as $department) {
			      $departments = explode(',',$department->inve_department_list);
			  }
			  if(in_array($inve_id,$departments, TRUE)&&$departments!=NULL){
				  $title = '没有上传记录';
				  if(user_access('create investigate department')){
					 $title = l('提交尽调材料','investigate_template/create/'.$node->id);
				  }
					 
				  $query = "SELECT id , name FROM " .
					           "{investigate_file_info} where guiding_fund_id = ? and type = ? and user_id = ?";
				  $queryResult = db_query($query, array( $node->id, 1, $user->uid));
				  foreach ($queryResult as $template) {
					  if($template->id>0)
						  {  	
							$title = l($template->name,'investigate_file/list/'.$template->id);	
						  }
				 }
				  $rows[] = array(
			      'data' => array(
			        l($node->name, 'guidingfund/list/'. $node->id),
			        $node->principal_name,
			        format_date($node->timestamp, 'custom', 'D, Y-m-d'),
			        $title,
			      )
			      );
			 }
		  }  
		  else{
		  	$title = l('查看评审材料','investigate_file/guidingfund/'. $node->id);
			$rows[] = array(
		      'data' => array(
		        l($node->name, 'guidingfund/list/'. $node->id),
		        $node->principal_name,
		        format_date($node->timestamp, 'custom', 'D, Y-m-d'),
		        $title,
		      )
		      );
		  }
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  }  
  else{
  	$html .= l('请先填写尽调机构信息！','investigatedepartment/create');
  }
  return ($html); 
}

